package com.example.comiccenter.Interceptor;

import com.alibaba.fastjson.JSON;
import com.example.comiccenter.utils.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.rmi.ServerException;
import java.util.HashMap;

public class CheckTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        HashMap<String, String> map = new HashMap<>();
        if (token == null){
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter pw = response.getWriter();
            map.put("code","401");
            map.put("msg","用户未登录");
            pw.write(JSON.toJSONString(map));
            System.out.println("用户未登录");
            return false;
        }
        if (JWTUtil.checkToken(token)){
            return true;
        }
        PrintWriter pw = response.getWriter();
        map.clear();
        map.put("code","402");
        map.put("msg","token验证失败");
        pw.write(JSON.toJSONString("token验证失败"));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
